<?php
include_once(dirname(__FILE__)."/classes/Zphoto.php");
/**
 * Class này hiển thị bảng trong csdl là bảng pl_gp_photo
 * @author nhat
 *
 */
class ZadminPhoto extends ZadminTab
{
	/**
	 * Hàm dựng 
	 * khai báo thông tin về bảng dữ liệu 
	 * các thao tác 
	 * các trường hiển thị
	 */
	public function __construct()
	{
		$id_zgallery_album = Tools::getValue('id_zgallery_album');
		if (!$id_zgallery_album) $id_zgallery_album=1; 
		global $cookie;
		$this->table = 'zgallery_photo';
	 	$this->className = 'Zphoto';
	 	$this->edit = true;
	 	$this->lang = true;
	 	$this->delete = true;
	 	$genders = array(0 => $this->l('Not Display'), 1 => $this->l('Display'), 2 => $this->l('Pending'));
		$this->fieldsDisplay = array(
			'id_zgallery_photo' => array('title' => $this->l('ID'), 'align' => 'center', 'width' => 53),
			'image' => array('title' => $this->l('Photo'), 'align' => 'center', 'image' => 'zgallery/img/photo/', 'width' => 45, 'orderby' => false, 'filter' => false, 'search' => false),
			'name' => array('title' => $this->l('Name'), 'align' => 'center', 'width' => 240),
			'nb_view' => array('title' => $this->l('Number View'), 'align' => 'center', 'width' => 23),
			'nb_like' => array('title' => $this->l('Number Like'), 'align' => 'center', 'width' => 23),
			'date_add' => array('title' => $this->l('Create Date'), 'type'=>'datetime' ,'align' => 'right', 'width' => 100),
			'active' => array('title' => $this->l('Status'), 'width' => 50, 'align' => 'center', 'callback'=>'printNewsIconActive', 'orderby' => false, 'type' => 'select', 'select' => $genders, 'filter_key' => 'a!active'),
		);
		$this->_filter = 'AND `id_zgallery_album` = '.(int)($id_zgallery_album);
		parent::__construct();
	}
	
	/**
	 * Display image aside object form
	 *
	 * @param integer $id Object id
	 * @param string $image Local image filepath
	 * @param integer $size Image width
	 * @param integer $id_image Image id (for products with several images)
	 * @param string $token Employee token used in the image deletion link
	 * @param boolean $disableCache When turned on a timestamp will be added to the image URI to disable the HTTP cache
	 *
	 * @global string $currentIndex Current URL in order to keep current Tab
	 */
	public function _displayImage($id, $image, $DIR,$size, $id_image = NULL, $token = NULL, $disableCache = false)
	{
		global $currentIndex;
		if (!isset($token) OR empty($token))
			$token = $this->token;
		
		if ($id AND file_exists($image))
			echo '
			<div id="image" >
				<img class="imgm" alt="" src="'.$DIR.'" style="width:'.$size.'px">
				<p align="center">'.$this->l('File size').' '.(filesize($image) / 1000).'kb</p>
			</div><br />';
	}
	/**
	 * Hàm lấy địa chỉ id  mà sẽ được tạo ra
	 * Hay lớn nhất
	 */
	function getNewId()
	{
		$rs = Db::getInstance()->ExecuteS('SELECT id_zgallery_photo FROM '._DB_PREFIX_.'zgallery_photo ORDER BY id_zgallery_photo DESC LIMIT 0,1');
		$row = $rs[0];
		return $row['id_zgallery_photo']+1;
	}
	/** 
	 * NHững thông tin được update sẽ lưu tại đây
	 * @param $token
	 */
	public function postProcess($token = NULL)
	{
		global $currentIndex;
		$_GET['tabs']=0;
		if (Tools::isSubmit('changeActivephoto') and Tools::getValue('id_zgallery_photo')){
			$id_zgallery_album=(int)Tools::getValue('id_zgallery_photo');
			$id = (int) Tools::getValue('id_zgallery_album',1);
			$obj = new Zphoto($id_zgallery_album);
			$update = Db::getInstance()->Execute(
				'UPDATE `'._DB_PREFIX_.'zgallery_photo` 
				SET active = '.($obj->active?0:1).' 
				WHERE `id_zgallery_photo` = '.(int)($obj->id));
			if (!$update)
				$this->_errors[] = Tools::displayError('An error occurred while updating customer.');
			if ($id==1)
				Tools::redirectAdmin($currentIndex.'&conf=5&token='.$this->token);
			else 
				Tools::redirectAdmin($currentIndex.'&id_zgallery_album='.$id.'&conf=5&token='.$this->token);
		}
		if (Tools::isSubmit('submitAdd'.$this->table)) {
			$obj = $this->loadObject(true);
			if ($obj->id==NULL){
				$target = dirname(__FILE__).'/img/photo/';
	
				$img_ext = substr($_FILES['image']['name'], strripos($_FILES['image']['name'], '.')); // strip name
				if(Tools::getValue('id_zgallery_photo')){
					$newfilename = 'Photo_'.$this->getFieldValue($obj, 'id_zgallery_photo').$img_ext;			
				}else{
					$newfilename = 'Photo_'.$this->getNewId().$img_ext;			
	
				} 
				$targetimg = $target.$newfilename;
				$fileimg = $_FILES['image']['name'];
				if($fileimg != ''){
					if($this->check($fileimg)){					
	
						if(move_uploaded_file($_FILES['image']['tmp_name'],$targetimg)==true){
							$_POST['image'] = $newfilename;
						}
					}else{
						$this->error = 1;
						$this->_errors[] = Tools::displayError('Images format not recognized, allowed formats are: .gif, .jpeg, .jpg, .png');
					}			
				}
			}
			else {
				if ($_FILES['image']['name']!="") {
					$target = dirname(__FILE__).'/img/photo/';
		
					$img_ext = substr($_FILES['image']['name'], strripos($_FILES['image']['name'], '.')); // strip name
					if(Tools::getValue('id_zgallery_photo')){
						$newfilename = 'Photo_'.$this->getFieldValue($obj, 'id_zgallery_photo').$img_ext;			
					}else{
						$newfilename = 'Photo_'.$this->getNewId().$img_ext;			
		
					} 
					$targetimg = $target.$newfilename;
					$fileimg = $_FILES['image']['name'];
					if($fileimg != ''){
						if($this->check($fileimg)){					
		
							if(move_uploaded_file($_FILES['image']['tmp_name'],$targetimg)==true){
								$_POST['image'] = $newfilename;
							}
						}else{
							$this->error = 1;
							$this->_errors[] = Tools::displayError('Images format not recognized, allowed formats are: .gif, .jpeg, .jpg, .png');
						}			
					}
				}
				else 
					$_POST['image'] = Zphoto::getNamePhoto ($obj->id);
			}
		}
		
		$this->_postProcess();
	}
	/**
	 * Giống hệt với postProcess cha 
	 * nhưng thay đổi ở hàm delete
	 */
	function _postProcess (){
		global $currentIndex, $cookie;
		if (!isset($this->table))
			return false;
		
		// set token
		$token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;

		// Sub included tab postProcessing
		$this->includeSubTab('postProcess', array('status', 'submitAdd1', 'submitDel', 'delete', 'submitFilter', 'submitReset'));

		/* Delete object image */
		if (isset($_GET['deleteImage']))
		{
			if (Validate::isLoadedObject($object = $this->loadObject()))
				if (($object->deleteImage()))
					Tools::redirectAdmin($currentIndex.'&add'.$this->table.'&'.$this->identifier.'='.Tools::getValue($this->identifier).'&conf=7&token='.$token);
			$this->_errors[] = Tools::displayError('An error occurred during image deletion (cannot load object).');
		}

		/* Delete object */
		elseif (isset($_GET['delete'.$this->table]))
		{
			if ($this->tabAccess['delete'] === '1')
			{
				if (Validate::isLoadedObject($object = $this->loadObject()) AND isset($this->fieldImageSettings))
				{
					// check if request at least one object with noZeroObject
					if (isset($object->noZeroObject) AND sizeof(call_user_func(array($this->className, $object->noZeroObject))) <= 1)
						$this->_errors[] = Tools::displayError('You need at least one object.').' <b>'.$this->table.'</b><br />'.Tools::displayError('You cannot delete all of the items.');
					else
					{
						$id = $_GET['id_zgallery_photo'];
						
						$name = Zphoto::getImageName ($id);
						Zphoto::_deleteImage($id,$name);
						$id_zgallery_album = Tools::getValue('id_zgallery_album');
						$category_url = empty($id_zgallery_album) ? '' : '&id_zgallery_album='.$id_zgallery_album;
						if ($this->deleted)
						{
							$object->deleted = 1;
							if ($object->update()) 
								Tools::redirectAdmin($currentIndex.'&conf=1&token='.$token.$category_url);
						}
						elseif ($object->delete()) {
							Tools::redirectAdmin($currentIndex.'&conf=1&token='.$token.$category_url);
						}
						$this->_errors[] = Tools::displayError('An error occurred during deletion.');
					}
				}
				else
					$this->_errors[] = Tools::displayError('An error occurred while deleting object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
			}
			else
				$this->_errors[] = Tools::displayError('You do not have permission to delete here.');
		}

		/* Change object statuts (active, inactive) */
		elseif ((isset($_GET['status'.$this->table]) OR isset($_GET['status'])) AND Tools::getValue($this->identifier))
		{
			if ($this->tabAccess['edit'] === '1')
			{
				if (Validate::isLoadedObject($object = $this->loadObject()))
				{
					if ($object->toggleStatus())
						Tools::redirectAdmin($currentIndex.'&conf=5'.((($id_category = (int)(Tools::getValue('id_category'))) AND Tools::getValue('id_product')) ? '&id_category='.$id_category : '').'&token='.$token);
					else
						$this->_errors[] = Tools::displayError('An error occurred while updating status.');
				}
				else
					$this->_errors[] = Tools::displayError('An error occurred while updating status for object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
			}
			else
				$this->_errors[] = Tools::displayError('You do not have permission to edit here.');
		}
		/* Move an object */
		elseif (isset($_GET['position']))
		{
			if ($this->tabAccess['edit'] !== '1')
				$this->_errors[] = Tools::displayError('You do not have permission to edit here.');
			elseif (!Validate::isLoadedObject($object = $this->loadObject()))
				$this->_errors[] = Tools::displayError('An error occurred while updating status for object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
			elseif (!$object->updatePosition((int)(Tools::getValue('way')), (int)(Tools::getValue('position'))))
				$this->_errors[] = Tools::displayError('Failed to update the position.');
			else
				Tools::redirectAdmin($currentIndex.'&'.$this->table.'Orderby=position&'.$this->table.'Orderway=asc&conf=5'.(($id_category = (int)(Tools::getValue($this->identifier))) ? ('&'.$this->identifier.'='.$id_category) : '').'&token='.$token);
				 Tools::redirectAdmin($currentIndex.'&'.$this->table.'Orderby=position&'.$this->table.'Orderway=asc&conf=5'.((($id_category = (int)(Tools::getValue('id_category'))) AND Tools::getValue('id_product')) ? '&id_category='.$id_category : '').'&token='.$token);
		}
		/* Delete multiple objects */
		elseif (Tools::getValue('submitDel'.$this->table))
		{
			if ($this->tabAccess['delete'] === '1')
			{
				if (isset($_POST[$this->table.'Box']))
				{
					$object = new $this->className();
					if (isset($object->noZeroObject) AND
						// Check if all object will be deleted
						(sizeof(call_user_func(array($this->className, $object->noZeroObject))) <= 1 OR sizeof($_POST[$this->table.'Box']) == sizeof(call_user_func(array($this->className, $object->noZeroObject)))))
						$this->_errors[] = Tools::displayError('You need at least one object.').' <b>'.$this->table.'</b><br />'.Tools::displayError('You cannot delete all of the items.');
					else
					{
						$result = true;
						if ($this->deleted)
						{
							foreach(Tools::getValue($this->table.'Box') as $id)
							{
								$toDelete = new $this->className($id);
								$toDelete->deleted = 1;
								$result = $result AND $toDelete->update();
							}
						}
						else
							$result = $object->deleteSelection(Tools::getValue($this->table.'Box'));

						if ($result) {
							$id_zgallery_album = Tools::getValue('id_zgallery_album');
							$category_url = empty($id_zgallery_album) ? '' : '&id_zgallery_album='.$id_zgallery_album;
							Tools::redirectAdmin($currentIndex.'&conf=2&token='.$token.$category_url);
							
						}
						$this->_errors[] = Tools::displayError('An error occurred while deleting selection.');
					}
				}
				else
					$this->_errors[] = Tools::displayError('You must select at least one element to delete.');
			}
			else
				$this->_errors[] = Tools::displayError('You do not have permission to delete here.');
		}

		/* Create or update an object */
		elseif (Tools::getValue('submitAdd'.$this->table))
		{
			
			/* Checking fields validity */
			$this->validateRules();
			
			if (!sizeof($this->_errors))
			{
				
				$id = (int)(Tools::getValue($this->identifier));
				
				/* Object update */
				if (isset($id) AND !empty($id))
				{
					if ($this->tabAccess['edit'] === '1' OR ($this->table == 'employee' AND $cookie->id_employee == Tools::getValue('id_employee') AND Tools::isSubmit('updateemployee')))
					{
						$object = new $this->className($id);
						if (Validate::isLoadedObject($object))
						{
							/* Specific to objects which must not be deleted */
							if ($this->deleted AND $this->beforeDelete($object))
							{
								// Create new one with old objet values
								$objectNew = new $this->className($object->id);
								$objectNew->id = NULL;
								$objectNew->date_add = '';
								$objectNew->date_upd = '';

								// Update old object to deleted
								$object->deleted = 1;
								$object->update();

								// Update new object with post values
								$this->copyFromPost($objectNew, $this->table);
								$result = $objectNew->add();
								if (Validate::isLoadedObject($objectNew))
									$this->afterDelete($objectNew, $object->id);
							}
							else
							{
								$this->copyFromPost($object, $this->table);
								$result = $object->update();
								$this->afterUpdate($object);
							}
							if (!$result)
								$this->_errors[] = Tools::displayError('An error occurred while updating object.').' <b>'.$this->table.'</b> ('.Db::getInstance()->getMsgError().')';
							elseif ($this->postImage($object->id) AND !sizeof($this->_errors))
							{
								$parent_id = (int)(Tools::getValue('id_parent', 1));
								// Specific back redirect
								if ($back = Tools::getValue('back'))
									Tools::redirectAdmin(urldecode($back).'&conf=4');
								// Specific scene feature
								if (Tools::getValue('stay_here') == 'on' || Tools::getValue('stay_here') == 'true' || Tools::getValue('stay_here') == '1')
									Tools::redirectAdmin($currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=4&updatescene&token='.$token);
								// Save and stay on same form
								if (Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
									Tools::redirectAdmin($currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=4&update'.$this->table.'&token='.$token);
								// Save and back to parent
								if (Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
									Tools::redirectAdmin($currentIndex.'&'.$this->identifier.'='.$parent_id.'&conf=4&token='.$token);
								// Default behavior (save and back)
								Tools::redirectAdmin($currentIndex.($parent_id ? '&'.$this->identifier.'='.$object->id : '').'&id_zgallery_album='.Zphoto::getParrent($object->id).'&conf=4&token='.$token);
								
								
							}
						}
						else
							$this->_errors[] = Tools::displayError('An error occurred while updating object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
					}
					else
						$this->_errors[] = Tools::displayError('You do not have permission to edit here.');
				}

				/* Object creation */
				else
				{
					if ($this->tabAccess['add'] === '1')
					{
						$object = new $this->className();
						$this->copyFromPost($object, $this->table);
						if (!$object->add())
							$this->_errors[] = Tools::displayError('An error occurred while creating object.').' <b>'.$this->table.' ('.mysql_error().')</b>';
						elseif (($_POST[$this->identifier] = $object->id /* voluntary */) AND $this->postImage($object->id) AND !sizeof($this->_errors) AND $this->_redirect)
						{
							$this->renameImage ($this->getNewId()-1);
							$parent_id = (int)(Tools::getValue('id_parent', 1));
							$this->afterAdd($object);
							// Save and stay on same form
							if (Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
								Tools::redirectAdmin($currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=3&update'.$this->table.'&token='.$token);
							// Save and back to parent
							if (Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
								Tools::redirectAdmin($currentIndex.'&'.$this->identifier.'='.$parent_id.'&conf=3&token='.$token);
							// Default behavior (save and back)
							Tools::redirectAdmin($currentIndex.($parent_id ? '&'.$this->identifier.'='.$object->id : '').'&id_zgallery_album='.Zphoto::getParrent($object->id).'&conf=3&token='.$token);
							
						}
					}
					else
						$this->_errors[] = Tools::displayError('You do not have permission to add here.');
				}
			}
			$this->_errors = array_unique($this->_errors);
		}

		/* Cancel all filters for this tab */
		elseif (isset($_POST['submitReset'.$this->table]))
		{
			$filters = $cookie->getFamily($this->table.'Filter_');
			foreach ($filters AS $cookieKey => $filter)
				if (strncmp($cookieKey, $this->table.'Filter_', 7 + Tools::strlen($this->table)) == 0)
					{
						$key = substr($cookieKey, 7 + Tools::strlen($this->table));
						/* Table alias could be specified using a ! eg. alias!field */
						$tmpTab = explode('!', $key);
						$key = (count($tmpTab) > 1 ? $tmpTab[1] : $tmpTab[0]);
						if (array_key_exists($key, $this->fieldsDisplay))
							unset($cookie->$cookieKey);
					}
			if (isset($cookie->{'submitFilter'.$this->table}))
				unset($cookie->{'submitFilter'.$this->table});
			if (isset($cookie->{$this->table.'Orderby'}))
				unset($cookie->{$this->table.'Orderby'});
			if (isset($cookie->{$this->table.'Orderway'}))
				unset($cookie->{$this->table.'Orderway'});
			unset($_POST);
		}

		/* Submit options list */
		elseif (Tools::getValue('submitOptions'.$this->table))
		{
			$this->updateOptions($token);
		}

		/* Manage list filtering */
		elseif (Tools::isSubmit('submitFilter'.$this->table) OR $cookie->{'submitFilter'.$this->table} !== false)
		{
			$_POST = array_merge($cookie->getFamily($this->table.'Filter_'), (isset($_POST) ? $_POST : array()));
			foreach ($_POST AS $key => $value)
			{
				/* Extracting filters from $_POST on key filter_ */
				if ($value != NULL AND !strncmp($key, $this->table.'Filter_', 7 + Tools::strlen($this->table)))
				{
					
					$key = Tools::substr($key, 7 + Tools::strlen($this->table));
					/* Table alias could be specified using a ! eg. alias!field */
					$tmpTab = explode('!', $key);
					$filter = count($tmpTab) > 1 ? $tmpTab[1] : $tmpTab[0];
					
					if ($field = $this->filterToField($key, $filter))
					{
						$type = (array_key_exists('filter_type', $field) ? $field['filter_type'] : (array_key_exists('type', $field) ? $field['type'] : false));
						if (($type == 'date' OR $type == 'datetime') AND is_string($value))
							$value = unserialize($value);
						$key = isset($tmpTab[1]) ? $tmpTab[0].'.`'.$tmpTab[1].'`' : '`'.$tmpTab[0].'`';
						if (array_key_exists('tmpTableFilter', $field))
							$sqlFilter = & $this->_tmpTableFilter;
						elseif (array_key_exists('havingFilter', $field))
							$sqlFilter = & $this->_filterHaving;
						else
							$sqlFilter = & $this->_filter;

						/* Only for date filtering (from, to) */
						if (is_array($value))
						{
							if (isset($value[0]) AND !empty($value[0]))
							{
								if (!Validate::isDate($value[0]))
									$this->_errors[] = Tools::displayError('\'from:\' date format is invalid (YYYY-MM-DD)');
								else
									$sqlFilter .= ' AND '.pSQL($key).' >= \''.pSQL(Tools::dateFrom($value[0])).'\'';
							}

							if (isset($value[1]) AND !empty($value[1]))
							{
								if (!Validate::isDate($value[1]))
									$this->_errors[] = Tools::displayError('\'to:\' date format is invalid (YYYY-MM-DD)');
								else
									$sqlFilter .= ' AND '.pSQL($key).' <= \''.pSQL(Tools::dateTo($value[1])).'\'';
							}
							
						}
						else
						{
							$sqlFilter .= ' AND ';
							if ($type == 'int' OR $type == 'bool')
								$sqlFilter .= (($key == $this->identifier OR $key == '`'.$this->identifier.'`' OR $key == '`active`') ? 'a.' : '').pSQL($key).' = '.(int)($value).' ';
							elseif ($type == 'decimal')
								$sqlFilter .= (($key == $this->identifier OR $key == '`'.$this->identifier.'`') ? 'a.' : '').pSQL($key).' = '.(float)($value).' ';
							elseif ($type == 'select')
								$sqlFilter .= (($key == $this->identifier OR $key == '`'.$this->identifier.'`') ? 'a.' : '').pSQL($key).' = \''.pSQL($value).'\' ';
							else
								$sqlFilter .= (($key == $this->identifier OR $key == '`'.$this->identifier.'`') ? 'a.' : '').pSQL($key).' LIKE \'%'.pSQL($value).'%\' ';
						}
						
					}
				}
			}
		}
		elseif (Tools::isSubmit('submitFields') AND $this->requiredDatabase AND $this->tabAccess['add'] === '1' AND $this->tabAccess['delete'] === '1')
		{
			if (!is_array($fields = Tools::getValue('fieldsBox')))
				$fields = array();

			$object = new $this->className();
			if (!$object->addFieldsRequiredDatabase($fields))
				$this->_errors[] = Tools::displayError('Error in updating required fields');
			else
				Tools::redirectAdmin($currentIndex.'&conf=4&token='.$token);
		}
	}
	/**
	 * Hiển thị nội dung chính
	 * @param unknown_type $token
	 */
	public function displayListContent($token = NULL)
	{
		/* Display results in a table
		 *
		 * align  : determine value alignment
		 * prefix : displayed before value
		 * suffix : displayed after value
		 * image  : object image
		 * icon   : icon determined by values
		 * active : allow to toggle status
		 */

		global $currentIndex, $cookie;
		$currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));

		$id_category = 1; // default categ

		$irow = 0;
		if ($this->_list AND isset($this->fieldsDisplay['position']))
		{
			$positions = array_map(create_function('$elem', 'return (int)($elem[\'position\']);'), $this->_list);
			sort($positions);
		}
		if ($this->_list)
		{
			$isCms = false;
			if (preg_match('/cms/Ui', $this->identifier))
				$isCms = true;
			$keyToGet = 'id_'.($isCms ? 'cms_' : '').'category'.(in_array($this->identifier, array('id_category', 'id_cms_category')) ? '_parent' : '');
			foreach ($this->_list AS $tr)
			{
				$id = $tr[$this->identifier];
				echo '<tr'.(array_key_exists($this->identifier,$this->identifiersDnd) ? ' id="tr_'.(($id_category = (int)(Tools::getValue('id_'.($isCms ? 'cms_' : '').'category', '1'))) ? $id_category : '').'_'.$id.'_'.$tr['position'].'"' : '').($irow++ % 2 ? ' class="alt_row"' : '').' '.((isset($tr['color']) AND $this->colorOnBackground) ? 'style="background-color: '.$tr['color'].'"' : '').'>
							<td class="center">';
				if ($this->delete AND (!isset($this->_listSkipDelete) OR !in_array($id, $this->_listSkipDelete)))
					echo '<input type="checkbox" name="'.$this->table.'Box[]" value="'.$id.'" class="noborder" />';
				echo '</td>';
				foreach ($this->fieldsDisplay AS $key => $params)
				{
					$tmp = explode('!', $key);
					$key = isset($tmp[1]) ? $tmp[1] : $tmp[0];
					echo '
					<td '.(isset($params['position']) ? ' id="td_'.(isset($id_category) AND $id_category ? $id_category : 0).'_'.$id.'"' : '').' class="'.((!isset($this->noLink) OR !$this->noLink) ? 'pointer' : '').((isset($params['position']) AND $this->_orderBy == 'position')? ' dragHandle' : ''). (isset($params['align']) ? ' '.$params['align'] : '').'" ';
					if (!isset($params['position']) AND (!isset($this->noLink) OR !$this->noLink))
						echo ' onclick="document.location = \''.$currentIndex.'&'.$this->identifier.'='.$id.($this->view? '&view' : '&update').$this->table.'&token='.($token!=NULL ? $token : $this->token).'\'">'.(isset($params['prefix']) ? $params['prefix'] : '');
					else
						echo '>';
					if (isset($params['active']) AND isset($tr[$key]))
						$this->_displayEnableLink($token, $id, $tr[$key], $params['active'], Tools::getValue('id_category'), Tools::getValue('id_product'));
					elseif (isset($params['activeVisu']) AND isset($tr[$key]))
						echo '<img src="../img/admin/'.($tr[$key] ? 'enabled.gif' : 'disabled.gif').'"
						alt="'.($tr[$key] ? $this->l('Enabled') : $this->l('Disabled')).'" title="'.($tr[$key] ? $this->l('Enabled') : $this->l('Disabled')).'" />';
					elseif (isset($params['position']))
					{
						if ($this->_orderBy == 'position' AND $this->_orderWay != 'DESC')
						{
							echo '<a'.(!($tr[$key] != $positions[sizeof($positions) - 1]) ? ' style="display: none;"' : '').' href="'.$currentIndex.
									'&'.$keyToGet.'='.(int)($id_category).'&'.$this->identifiersDnd[$this->identifier].'='.$id.'
									&way=1&position='.(int)($tr['position'] + 1).'&token='.($token!=NULL ? $token : $this->token).'">
									<img src="../img/admin/'.($this->_orderWay == 'ASC' ? 'down' : 'up').'.gif"
									alt="'.$this->l('Down').'" title="'.$this->l('Down').'" /></a>';
							echo '<a'.(!($tr[$key] != $positions[0]) ? ' style="display: none;"' : '').' href="'.$currentIndex.
									'&'.$keyToGet.'='.(int)($id_category).'&'.$this->identifiersDnd[$this->identifier].'='.$id.'
									&way=0&position='.(int)($tr['position'] - 1).'&token='.($token!=NULL ? $token : $this->token).'">
									<img src="../img/admin/'.($this->_orderWay == 'ASC' ? 'up' : 'down').'.gif"
									alt="'.$this->l('Up').'" title="'.$this->l('Up').'" /></a>';						}
						else
							echo (int)($tr[$key] + 1);
					}
					elseif (isset($params['image']))
					{
						
						echo '<img src="'._MODULE_DIR_.$params['image'].$tr['image'].'"  height="80" alt="ZadminGallery"/>';
//						// item_id is the product id in a product image context, else it is the image id.
//						$item_id = isset($params['image_id']) ? $tr[$params['image_id']] : $id;
//						// If it's a product image
//						if (isset($tr['id_image']))
//						{
//							$image = new Image((int)$tr['id_image']);
//							$path_to_image = _PS_MODULE_DIR_.'zgallery'.$params['image'].'/'.$image->getExistingImgPath().'.'.$this->imageType;
//						}else
//							$path_to_image = _PS_IMG_DIR_.$params['image'].'/'.$item_id.(isset($tr['id_image']) ? '-'.(int)($tr['id_image']) : '').'.'.$this->imageType;
//						
//						echo cacheImage($path_to_image, $this->table.'_mini_'.$item_id.'.'.$this->imageType, 45, $this->imageType);
					}
					elseif (isset($params['icon']) AND (isset($params['icon'][$tr[$key]]) OR isset($params['icon']['default'])))
						echo '<img src="../img/admin/'.(isset($params['icon'][$tr[$key]]) ? $params['icon'][$tr[$key]] : $params['icon']['default'].'" alt="'.$tr[$key]).'" title="'.$tr[$key].'" />';
					elseif (isset($params['price']))
						echo Tools::displayPrice($tr[$key], (isset($params['currency']) ? Currency::getCurrencyInstance((int)($tr['id_currency'])) : $currency), false);
					elseif (isset($params['float']))
						echo rtrim(rtrim($tr[$key], '0'), '.');
					elseif (isset($params['type']) AND $params['type'] == 'date')
						echo Tools::displayDate($tr[$key], (int)$cookie->id_lang);
					elseif (isset($params['type']) AND $params['type'] == 'datetime')
						echo Tools::displayDate($tr[$key], (int)$cookie->id_lang, true);
					elseif (isset($tr[$key]))
					{
						$echo = ($key == 'price' ? round($tr[$key], 2) : isset($params['maxlength']) ? Tools::substr($tr[$key], 0, $params['maxlength']).'...' : $tr[$key]);
						echo isset($params['callback']) ? call_user_func_array(array($this->className, $params['callback']), array($echo, $tr)) : $echo;
					}
					else
						echo '--';

					echo (isset($params['suffix']) ? $params['suffix'] : '').
					'</td>';
				}

				if ($this->edit OR $this->delete OR ($this->view AND $this->view !== 'noActionColumn'))
				{
					echo '<td class="center" style="white-space: nowrap;">';
					if ($this->view)
						$this->_displayViewLink($token, $id);
					if ($this->edit)
						$this->_displayEditLink($token, $id);
					if ($this->delete AND (!isset($this->_listSkipDelete) OR !in_array($id, $this->_listSkipDelete)))
						$this->_displayDeleteLink($token, $id);
					if ($this->duplicate)
						$this->_displayDuplicate($token, $id);
					echo '</td>';
				}
				echo '</tr>';
			}
		}
	}
	function loadJS_CSS()
	{
		global $cookie;
		$iso = Language::getIsoById((int)($cookie->id_lang));
		$isoTinyMCE = (file_exists(_PS_ROOT_DIR_.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en');
		$ad = dirname($_SERVER["PHP_SELF"]);
		echo '
			<script type="text/javascript">
			var iso = \''.$isoTinyMCE.'\' ;
			var pathCSS = \''._THEME_CSS_DIR_.'\' ;
			var ad = \''.$ad.'\' ;
			</script>
			<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tiny_mce/tiny_mce.js"></script>';
			
			echo '
			<script type="text/javascript">	
				tinyMCE.init({
					mode : "specific_textareas",
					theme : "advanced",
					skin:"cirkuit",
					editor_selector : "mceEditor",
					editor_deselector : "noEditor",
					plugins : "safari,pagebreak,style,table,advimage,advlink,inlinepopups,media,contextmenu,paste,fullscreen,xhtmlxtras,preview",
					// Theme options
					theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
					theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,,|,forecolor,backcolor",
					theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,media,|,ltr,rtl,|,fullscreen",
					theme_advanced_buttons4 : "styleprops,|,cite,abbr,acronym,del,ins,attribs,pagebreak",
					theme_advanced_toolbar_location : "top",
					theme_advanced_toolbar_align : "left",
					theme_advanced_statusbar_location : "bottom",
					theme_advanced_resizing : false,
					content_css : pathCSS+"global.css",
					document_base_url : ad,
					width: "600",
					height: "auto",
					font_size_style_values : "8pt, 10pt, 12pt, 14pt, 18pt, 24pt, 36pt",
					elements : "nourlconvert,ajaxfilemanager",
					file_browser_callback : "ajaxfilemanager",
					entity_encoding: "raw",
					convert_urls : false,
					language : iso
				});
			</script>'; 
	}
	
	function loadJaS_CSS2()
	{
		global $cookie;
		$iso = Language::getIsoById((int)($cookie->id_lang));
		$isoTinyMCE = (file_exists(_PS_ROOT_DIR_.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en');
		$ad = dirname($_SERVER["PHP_SELF"]);
		echo '
			<script type="text/javascript">
			var iso = \''.$isoTinyMCE.'\' ;
			var pathCSS = \''._THEME_CSS_DIR_.'\' ;
			var ad = \''.$ad.'\' ;
			</script>
			<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tiny_mce/tiny_mce.js"></script>
			<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tinymce.inc.js"></script>';
		?>
		<script type="text/javascript">
			function copy2friendlyURL()
			{
				$('input#freurl_' + id_language).val(str2url($('input#name_' + id_language).val().replace(/^[0-9]+\./, ''), 'UTF-8'));
			}
		</script>
		<?php
	}
	
	public function display($token = NULL)
	{
		global $currentIndex, $cookie;
		
		if (($id_zgallery_album = (int)Tools::getValue('id_zgallery_album')))
			$currentIndex .= '&id_zgallery_album='.$id_zgallery_album;

		$this->getList((int)($cookie->id_lang), !$cookie->__get($this->table.'Orderby') ? NULL : NULL, !$cookie->__get($this->table.'Orderway') ? 'ASC' : NULL);
	//	echo '<h3>'.(!$this->_listTotal ? ($this->l('There are no subcategories')) : ($this->_listTotal.' '.($this->_listTotal > 1 ? $this->l('subcategories') : $this->l('subcategory')))).' '.$this->l('in category').' "'.stripslashes($this->_category->getName()).'"</h3>';
		if ($this->tabAccess['add'] === '1')
			echo '<a href="'.__PS_BASE_URI__.substr($_SERVER['PHP_SELF'], strlen(__PS_BASE_URI__)).'?tab=ZadminGallery&add'.$this->table.'&id_zgallery_album='.Tools::getValue('id_zgallery_album').'&token='.($token!=NULL ? $token : $this->token).'"><img src="../img/admin/add.gif" border="0" /> '.$this->l('Add a new photo').'</a>';
		echo '<div style="margin:10px;">';
		$this->displayList($token);
		echo '</div>';
	}
	/**
	 * Manage page display (form, list...)
	 *
	 * @global string $currentIndex Current URL in order to keep current Tab
	 */
	public function displayList($token = NULL)
	{
		global $currentIndex;
		
		/* Display list header (filtering, pagination and column names) */
		$this->displayListHeader($token);
		if (!sizeof($this->_list))
			echo '<tr><td class="center" colspan="'.(sizeof($this->fieldsDisplay) + 2).'">'.$this->l('No items found').'</td></tr>';

		/* Show the content of the table */
		$this->displayListContent($token);

		/* Close list table and submit button */
		$this->displayListFooter($token);
	}
	
	
	/**
	 * Hiển thị Form 
	 */
	public function displayForm ($isMainTab = true){
		global $currentIndex,$cookie;	// dia chi index hien tai
		parent::displayForm();
		$this->loadJS_CSS();
		$this->loadJaS_CSS2();
		$id_zgallery_photo=Tools::getValue ('id_zgallery_photo');
		if (Tools::isSubmit('updatezgallery_photo')){
			$id_zgallery_album=Zphoto::getParrent ($id_zgallery_photo);
		}
		else {
			$id_zgallery_album=Tools::getValue ('id_zgallery_album');
			if (!$id_zgallery_album) $id_zgallery_album=1;
		}
		$langtags = 'title¤description¤alt¤freurl';
		$obj = new Zphoto ($id_zgallery_photo);
		if ($obj->id)
			$currentIndex .= '&id_zgallery_photo='.$obj->id;
		echo '<form action="'.$currentIndex.'&submitAdd'.$this->table.'=1&token='.$this->token.'" method="post" enctype="multipart/form-data">
			'.($obj->id ? '<input type="hidden" name="id_'.$this->table.'" value="'.$obj->id.'" /> ' : '');
		echo '<input type="hidden" name="id_zgallery_album" value="'.$id_zgallery_album.'"/>';
		echo '
			<fieldset style="width:900px;">
				<legend>'.$this->l('Add a new image to this album').'</legend> ';
		echo $this->addElement('text',array (
								'label' => 'Name',
								'name' => 'name',
								'langtags' => $langtags,
								'width' => 200,
								'note' => '',
								'more' => 'onkeyup="copy2friendlyURL();"'
		),true);
		
		echo '
				<label>'.$this->l('Album').': </label>
				<div class="margin-form">
					<select name="id_zgallery_album">';
		$Albums = Zphoto::getAlbum((int)($cookie->id_lang), false);
		Zphoto::recurseAlbum($Albums, $this->getFieldValue($obj, 'id_zgallery_album'));

		echo '
					</select>
				</div>';
		
		echo $this->addElement('area',array (
								'label' => 'Description',
								'name' => 'description',
								'langtags' => $langtags,
								'width' => 200,
								'note' => '',
								'more' => ''
		),true);
		
		echo '
		<label>'.$this->l('Photo').':</label>
		<div class="margin-form">
		';
		echo 		$this->_displayImage($obj->id, _PS_MODULE_DIR_.'zgallery/img/photo/'.Zphoto::getNamePhoto ($obj->id) ,_MODULE_DIR_.'zgallery/img/photo/'.Zphoto::getNamePhoto ($obj->id) ,350, NULL, Tools::getAdminToken('ZadminGallery'.(int)(Tab::getIdFromClassName('ZadminGallery')).(int)($cookie->id_lang)), true);
		echo '
			<input type="file" id="image" name="image" /><sup> *</sup>
			<p>'.$this->l('Format:').' JPG, GIF, PNG. '.$this->l('Filesize:').' '.($this->maxImageSize / 1000).''.$this->l('Kb max.').'
		</div>
		';
		
//		echo $this->addElement('text',array (
//								'label' => 'Friend URL',
//								'name' => 'freurl',
//								'langtags' => $langtags,
//								'width' => 200,
//								'note' => '',
//								'more' => ''
//		),true);
		
		echo $this->addElement('text',array (
								'label' => 'Random lucky member',
								'name' => 'random_lucky_member',
								'value' => $obj->random_lucky_member,
								'width' => 200,
								'note' => 'Will be calculated as %, please enter the number from 0-100',
								'more' => ''
		));
		
//		echo $this->addElement('text',array (
//								'label' => 'Number view',
//								'name' => 'nb_view',
//								'width' => 50,
//								'value' => $obj->nb_view,
//								'note' => 'Number peoples view picture, you can not edit',
//								'more' => 'readonly="readonly"'
//		));
//		
//		echo $this->addElement('text',array (
//								'label' => 'Number Like',
//								'name' => 'nb_like',
//								'width' => 50,
//								'value' => $obj->nb_like,
//								'note' => 'Number peoples like picture, you can not edit',
//								'more' => 'readonly="readonly"'
//		));
		
		
		echo $this->addElement('text',array (
								'label' => 'Limit Like',
								'name' => 'limit_like',
								'value' => $obj->limit_like,
								'width' => 50,
								'note' => 'Set 0 if not limited',
								'more' => ''
		));
		
		echo $this->addElement('yesno',array (
								'label' => 'Allow Like',
								'name' => 'allow_like',
								'width' => 200,
								'value' => $obj->active,
								'note' => '',
								'more' => ''
		));
		
		echo $this->addElement('yesno',array (
								'label' => 'Active',
								'name' => 'active',
								'width' => 200,
								'value' => $obj->active,
								'note' => '',
								'more' => ''
		));
		
		echo '
			<div class="margin-form">
				<input type="submit" value="'.$this->l('Save').'" name="submitAdd'.$this->table.'" class="button" /> 			</div>
			<div class="small"><sup>*</sup> '.$this->l('Required field').'</div>
			</fieldset>
		</form>';
		
	}
/* End Override Admin tab*/
	public $upload_type	= array('jpg', 'jpeg', 'gif', 'png');
	function check($filename){
		$start	= strrpos($filename, ".");
		if ( $start < strlen($filename) ){
			$user_type	= strtolower(substr($filename, $start+1));
			if ( in_array($user_type, $this->upload_type) ){
				return true;
			}
		}
		return false;
	}
	/**
	 * Thay đổi tên cho file upload
	 * @param unknown_type $id
	 */
	public function renameImage ($id) {
		$nameImageOld = Zphoto::getImageName ($id);
		$nameImage = substr($nameImageOld, strripos($nameImageOld, '.')); // strip name
		$query = '
			UPDATE `'._DB_PREFIX_.'zgallery_photo` SET `image`="Photo_'.$id.$nameImage.'" WHERE (`id_zgallery_photo`='.$id.')
		';
		$results = Db::getInstance()->Execute($query);
		$target = dirname(__FILE__).'/img/photo/';
		rename($target.$nameImageOld, $target."Photo_$id$nameImage");
		if (file_exists($target.$nameImage) AND !unlink($target.$nameImage))
			return true;
		return false;
	}
	
}
